from django.conf import settings
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseBadRequest
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required
from admin_forms import FlickrSearchForm
from utils.flickr import FlickrPhoto
from django.utils import simplejson 
import flickrapi
import urllib

@staff_member_required
def flickr_search(request, id=None):
	print "flickr search"
	# If the form has been submitted...
	if(len(request.GET)>0 and request.GET.get('text')):
		form = FlickrSearchForm(request.GET) # A form bound to the GET data
		if form.is_valid(): # All validation rules pass
			form_dict = form.cleaned_data
			# Make sure page request is an int. If not, deliver first page.
			try:
				page = int(request.GET.get('page', '1'))
			except ValueError:
				page = 1
			text =  form.cleaned_data['text']
			response = {'form':form,'text':  text }
			# Process the data in form.cleaned_data
			searchFlickr( text, page ,response)
			return render_to_response("admin/djangollery/flickrphoto/search.html",response,context_instance=RequestContext(request))
	else:
		form = FlickrSearchForm() # An unbound form
	return render_to_response("admin/djangollery/flickrphoto/search.html",{'form':form},context_instance=RequestContext(request))

@staff_member_required
def flickr_select(request, id=None):
	# If the form has been submitted...
	if(len(request.GET)>0 and request.GET.get('id')):
		id = request.GET.get('id')
		print "Seleccionada imagen " + id
		sizes  = getPhoto(id)
		response = simplejson.dumps(sizes)
		return HttpResponse(response)
	else:
		print "Error peticion no valida"
		return HttpResponseBadRequest()



def searchFlickr( text , page , response):
    photos = []
    flickr = flickrapi.FlickrAPI(settings.FLICKR_API_KEY)
    rspSet = flickr.photos_search(text=text, page=page, per_page=settings.FLICKR_PER_PAGE, privacy_filter=1,safe_search=1 )  
    if ( rspSet.attrib['stat'] == 'ok' ):
        photosSet=rspSet.find('photos')        
        pages = int(photosSet.attrib['pages'])
        photoSet = photosSet.findall('photo')
        for p in photoSet:
            photo = FlickrPhoto(p.attrib['id'],p.attrib['secret'],p.attrib['farm'],p.attrib['server'])
            photos.append(photo)
        response['photos'] = photos
        response['page']  = page
        response['pages']  = pages
        if ( page > 1 ):
            response['previous_page']=page-1
        if ( page < pages ):
            response['next_page']=page+1
        print "Ok al recuperar fotos"
    else:
        print "Error al recuperar las fotos"

def getPhoto( id ):
	result = {}
	flickr = flickrapi.FlickrAPI(settings.FLICKR_API_KEY)
	rspSet = flickr.photos_getSizes(photo_id=id )
	if ( rspSet.attrib['stat'] == 'ok' ):
		sizeSet=rspSet.find('sizes').findall('size')
		for s in sizeSet:
			result[s.attrib['label']]=s.attrib['source']
		if( 'Thumbnail' not in result and 'Square' in result):
			result['Thumbnail'] = result['Square']
		if( 'Medium' not in result and 'Small' in result):
			result['Medium'] = result['Small']
		if( 'Original' not in result and 'Large' in result):
			result['Original'] = result['Large']
		elif( 'Original' not in result and 'Medium' in result):
			result['Original'] = result['Medium']
		elif( 'Original' not in result and 'Small' in result):
			result['Original'] = result['Small']
		result['status']='ok'
	else:
		result['status']='error'
		print "Error al recuperar los tamaos de las fotos"
	return result
